package pl.edu.agh.inpema.core.components.impl;

import java.util.List;

import javax.jms.JMSException;

import pl.edu.agh.inpema.core.components.AnalyzerUtil;
import pl.edu.agh.inpema.core.dataBase.DataBase;
import pl.edu.agh.inpema.core.model.Message;
import pl.edu.agh.inpema.core.queue.Queue;
import pl.edu.agh.inpema.core.queue.QueueMessage;

public class AnalyzerUtilImpl implements AnalyzerUtil {
	
	private String analyzerName;
	
	private DataBase dataBase;
	private Queue queue;
	
	private static final int QUEUE_TIMEOUT = 250;
	
	public String getAnalyzerName() {
		return this.analyzerName;
	}
	
	public void setAnalyzerName(String analyzerName) {
		this.analyzerName = analyzerName;
	}
	
	public Message getNextMessage() {
		try {
			QueueMessage queueMessage = queue.getMessageForAnalyzer(this.analyzerName, QUEUE_TIMEOUT);
			if (queueMessage == null) {
				//System.out.println(analyzerName + ": no messages");
				return null;
			}
			int messageId = queueMessage.getMessageId();		
			Message message = dataBase.getMessage(messageId);
			//System.out.println(analyzerName + ": read message - "+queueMessage.getMessageId());
			return message;
		} catch (JMSException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public int getResultId(int profileId) {
		Integer resultId = dataBase.getAnalyzeResultId(this.analyzerName, profileId);
		if (resultId == null) {
			resultId = dataBase.addAnalyzeResultId(this.analyzerName, profileId);
		}
		return resultId;
	}
	
	public List<Object> getResultObjects(int resultId, Class cls) {
		return dataBase.getResultObject(resultId, cls);
	}
	
	public void addResultObject(Object obj) {
		//System.out.println(analyzerName + ": addResultObject");
		dataBase.addResultObject(this.analyzerName, obj);
	}
	
	public void setDataBase(DataBase dataBase) {
		this.dataBase = dataBase;
	}
	public void setQueue(Queue queue) {
		this.queue = queue;
	}
}
